<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript" charset="utf-8" src="${ctx}/static/inspinia/js/plugins/ueditor-1.4.3.3/ueditor.config.js"></script>
    <script type="text/javascript" charset="utf-8" src="${ctx}/static/inspinia/js/plugins/ueditor-1.4.3.3/_examples/editor_api.js"></script>
    <script type="text/javascript" charset="utf-8" src="${ctx}/static/inspinia/js/plugins/ueditor-1.4.3.3/lang/zh-cn/zh-cn.js"></script>
</head>

<body>

<div id="wrapper">
    <div class="gray-bg">
        <div class="wrapper wrapper-content animated fadeInRight">
            <div class="row">
                <div class="col-lg-12">
                    <div class="ibox float-e-margins">
                        <div class="ibox-content">
                            <form method="get" action="${ctx}/medical/resident/save" class="form-horizontal" id="resident_form">
                                <div class="form-group">
                                    <label class="col-sm-2 control-label">姓名</label>
                                    <div class="col-sm-3">
                                        <input id="title" type="text" class="form-control"
                                               placeholder="请输入" value="${data.title}" name="title" required>
                                    </div>
                                    <label class="col-sm-2 control-label">身份证号</label>
                                    <div class="col-sm-3">
                                        <input type="hidden" name="cardtype" value="1"/>
                                        <input id="idcard" type="text" class="form-control"
                                               placeholder="请输入" value="${data.idcard}" name="idcard" required>
                                    </div>
                                    <label id="sign_label" class="control-label" style="text-align: left;
                                    color: red; margin-top: 2px;"></label>
                                </div>
                                <div class="form-group">
                                    <label class="col-sm-2 control-label">性别</label>
                                    <div class="col-sm-3">
                                        <select class="form-control" name="sex" id="sex">
                                            <option value="1">男</option>
                                            <option value="2">女</option>
                                        </select>
                                    </div>
                                    <label class="col-sm-2 control-label">联系电话</label>
                                    <div class="col-sm-3">
                                        <input id="mobile" type="text" class="form-control"
                                               <%--style="-webkit-appearance: none;-moz-appearance: textfield;"--%>
                                               placeholder="请输入" value="${data.mobile}" name="mobile" required>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-sm-2 control-label">所在县区</label>
                                    <div class="col-sm-3">
                                        <select class="form-control" name="district_id" id="district_id" required>
                                            <c:forEach items="${districts}" var="item">
                                                <option value="${item.id}">${item.title}</option>
                                            </c:forEach>
                                        </select>
                                    </div>
                                    <label class="col-sm-2 control-label">所在街道</label>
                                    <div class="col-sm-3">
                                        <select class="form-control" name="town_id" id="town_id" required>
                                            <option value=""></option>
                                            <c:forEach items="${towns}" var="item">
                                                <option value="${item.id}">${item.title}</option>
                                            </c:forEach>
                                        </select>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-sm-2 control-label">详细地址</label>
                                    <div class="col-sm-8">
                                        <input id="address" type="text" class="form-control" required
                                               placeholder="请输入" value="${data.address}" name="address">
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="col-sm-2 control-label">签约团队</label>
                                    <div class="col-sm-3">
                                        <input type="text" class="form-control"
                                               placeholder="请输入" value="${team.teamName}" readonly>
                                    </div>
                                    <label class="col-sm-2 control-label">签约机构</label>
                                    <div class="col-sm-3">
                                        <input type="text" class="form-control"
                                               placeholder="请输入" value="${team.hospitalName}" readonly>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-sm-2 control-label">签约周期</label>
                                    <div class="col-sm-3">
                                        <div class="input-group date" datepicker>
                                            <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                                            <input type="text" id="signTime" name="signTime" required
                                                   placeholder="开始日期" class="form-control form-filter" readonly>
                                        </div>
                                    </div>
                                    <label class="col-sm-2 control-label">--</label>
                                    <div class="col-sm-3">
                                        <div class="input-group date">
                                            <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                                            <input type="text" id="expireTime" name="expireTime"
                                                   placeholder="结束日期" class="form-control form-filter" readonly>
                                        </div>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-sm-2 control-label">备注</label>
                                    <div class="col-sm-8">
                                        <input type="text" name="memo" class="form-control" placeholder="请输入">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-sm-2 control-label m-t-sm7">*人群分类</label>
                                    <div class="col-sm-9">
                                        <c:forEach items="${kv}" var="items">
                                            <input type="checkbox" class="check-style"
                                                   id="${items.key}" title="key" onclick="isCheck(this)">
                                            <span style="margin-right: 5px;">${items.value}</span>
                                        </c:forEach>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="col-sm-2 control-label">*身份证</label>
                                    <div class="col-sm-2">
                                        <input  type="hidden" id="src" name="image1" value="" required/>
                                        <div class="imager" id="srcView">
                                            <%--<c:choose>
                                                <c:when test="${not empty company.image}">
                                                    <img src="${company.image}" width="100%" height="100%">
                                                </c:when>
                                                <c:otherwise>--%>
                                                    <img src="${ctx}/static/inspinia/img/default_pic_no.jpg" width="100%" height="100%">
                                              <%--  </c:otherwise>
                                            </c:choose>--%>
                                        </div>
                                    </div>
                                    <div class="col-sm-3 upload-img-pt25">
                                        <div class="upload f-fl" id="uploaderLogoUrl"></div>
                                        <div class="tip f-fl upload-img-pt10"><span class="upload-img-ml6">建议上传：676*520</span></div>
                                    </div>

                                    <div class="col-sm-2">
                                        <input  type="hidden" id="src1" name="image2" value="" required/>
                                        <div class="imager" id="srcView1">
                                            <img src="${ctx}/static/inspinia/img/default_pic_no.jpg" width="100%" height="100%">
                                        </div>
                                    </div>
                                    <div class="col-sm-3 upload-img-pt25">
                                        <div class="upload f-fl" id="uploaderLogoUrl1"></div>
                                        <div class="tip f-fl upload-img-pt10"><span class="upload-img-ml6">建议上传：676*520</span></div>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="col-sm-2 control-label">*签约凭证</label>
                                    <div class="col-sm-2">
                                        <input  type="hidden" id="src2" name="signingImages" value="" required/>
                                        <div class="imager" id="srcView2">
                                            <img src="${ctx}/static/inspinia/img/default_pic_no.jpg" width="100%" height="100%">
                                        </div>
                                    </div>
                                    <div class="col-sm-3 upload-img-pt25">
                                        <div class="upload f-fl" id="uploaderLogoUrl2"></div>
                                        <div class="tip f-fl upload-img-pt10"><span class="upload-img-ml6">建议上传：676*520</span></div>
                                    </div>
                                </div>


                                <div class="hr-line-dashed"></div>
                                <div class="form-group">
                                    <div class="col-sm-4 col-sm-offset-2">
                                        <button class="btn" type="button" onclick="save()">保 存</button>
                                        <%--<a href="#" onclick="closeWin()" class="btn">  取消</a>--%>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript" src="${ctx}/static/inspinia/js/plugins/LD.sot/multiupf/uploadify2/jquery.uploadify.min.js"></script>
<script type="text/javascript" src="${ctx}/static/inspinia/js/plugins/LD.sot/multiupf/uploadify2/swfobject.js"></script>
<script type="text/javascript" src="${ctx}/static/inspinia/js/plugins/LD.sot/multiupf/multiupf.uploadify2.js"></script>
<script>
    Date.prototype.format = function(fmt) {
        var o = {
            "M+": this.getMonth() + 1, //月份
            "d+": this.getDate(), //日
            "h+": this.getHours(), //小时
            "m+": this.getMinutes(), //分
            "s+": this.getSeconds(), //秒
            "q+": Math.floor((this.getMonth() + 3) / 3), //季度
            "S": this.getMilliseconds() //毫秒
        };
        if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    };

    var defaultOption = '<option value=""></option>';

    $(document).ready(function() {
        $('#district_id').change(function() {
            var value = $(this).val();
            if (!value) {
                $('#town_id').html(defaultOption);
            } else {
                var html = getSubRegion(value);
                $('#town_id').html(html);
            }
        });

        init_src();

        $('#idcard').blur(function() {// 签约状态检查
            var idcard = $(this).val();
            signCheck(idcard);
        });

        $('#signTime').change(setExpireTime);
        $('#district_id').val(404345);
    });

    function init() {
        $("input[title='key']:checked").each(function(){
            $(this).attr("checked", false);
        });
    }

    function isCheck(self){
        var checked = $(self).is(':checked');
        var id = $(self).attr('id');
        if (checked) {
            if (id == "01") {
                $("input[id=" + '02' + "]").prop("checked", false);
                $("input[id=" + '03' + "]").prop("checked", false);
                $("input[id=" + '10' + "]").prop("checked", false);
            } else if (id == "02") {
                $("input[id=" + '01' + "]").prop("checked", false);
                $("input[id=" + '03' + "]").prop("checked", false);
                $("input[id=" + '10' + "]").prop("checked", false);
            } else if (id == "03") {
                $("input[id=" + '02' + "]").prop("checked", false);
                $("input[id=" + '01' + "]").prop("checked", false);
                $("input[id=" + '10' + "]").prop("checked", false);
            } else if (id == "10") {
                init();
                $("input[id=" + '10' + "]").prop("checked", true);
            }else if(id == "11"){
                $("input[id="+'12'+"]").prop("checked", false);
                $("input[id="+'10'+"]").prop("checked", false);
            }else if(id == "12"){
                $("input[id="+'11'+"]").prop("checked", false);
                $("input[id="+'10'+"]").prop("checked", false);
            } else {
                $("input[id=" + '10' + "]").prop("checked", false);
            }
        }
    }

    function setExpireTime() {
        var value = $('#signTime').val();
        if (value) {
            var arr = value.split('-');
            var date = new Date(Number(arr[0]) + 1, Number(arr[1]) - 1, Number(arr[2]));
            var new_y = date.getFullYear(), new_m = date.getMonth(), new_d = date.getDate();
            $('#expireTime').val(date.format("yyyy-MM-dd"));
        }
    }

    function signCheck(idcard) {
        if (!idcard) {
            $('#sign_label').html('');
            return;
        }
        $.ajax({
            cache: false,
            type: "POST",
            url: "${ctx}/medical/resident/signCheck",
            dataType: "json",
            data: {idcard: idcard},
            async: false,
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                var msg = "操作失败,错误代码[" + XMLHttpRequest.status + "]";
                parent.layer.alert(msg, {icon: 5, time: 2000});
            },
            success: function (res) {
                $('#sign_label').html('');
                if (res.code == 0) {
                    if (res.data.status != 0) {
                        $('#sign_label').html('该身份证已签约');
                        parent.layer.alert('该身份证已签约！', {icon: 5, time: 2000});
                    } else {
                        ehrCheck(idcard);
                    }
                } else {
                    $('#sign_label').html('查询签约状态失败');
                    parent.layer.alert('查询签约状态失败！', {icon: 5, time: 2000});
                }
            }
        });
    }

    function ehrCheck(idcard) {// 检查是否创建过创业公卫健康档案
        $('#sign_label').html('正在查询健康档案...');
        $.ajax({
            cache: false,
            type: "POST",
            url: "${ctx}/medical/resident/ehrCheck",
            dataType: "json",
            data: {idcard: idcard},
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $('#sign_label').html('');
            },
            success: function (res) {
                $('#sign_label').html('');
                if (res.code != 200) {
                    $('#sign_label').html('请先建立健康档案！');
                    parent.layer.alert('该居民尚未建立健康档案，请先建立档案！', {icon: 5, time: 2000});
                }
            }
        });
    }

    function getSubRegion(id) {
        var regions = [];
        $.ajax({
            cache: false,
            type: "POST",
            url: "${ctx}/medical/resident/getChildRegions",
            dataType: "json",
            data: {regionId: id},
            async: false,
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                var msg = "操作失败,错误代码[" + XMLHttpRequest.status + "]";
                parent.layer.alert(msg, {icon: 5, time: 2000});
            },
            success: function (data) {
                regions = data;
            }
        });
        return buildOptions(regions);
    }

    function buildOptions(regions) {
        var html = defaultOption;
        for (var i = 0; i < regions.length; i++) {
            var region = regions[i];
            html += '<option value="' + region.id + '">' + region.title + '</option>';
        }
        return html;
    }

    function saveqyinfo() {// 通知公卫系统该居民已签约成功
        var idcard = $('#idcard').val();
        var sxsj = $('#signTime').val();
        var zzsj = $('#expireTime').val();

        $.ajax({
            cache: false,
            type: "POST",
            url: "${ctx}/medical/resident/saveqyinfo",
            dataType: "json",
            data: {"idcard":idcard,"sxsj":sxsj,"zzsj":zzsj},
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                var msg = '添加成功，更新基层医疗签约状态失败，请及时处理';
                parent.layer.alert(msg, {icon: 1}, function(ind){
                    parent.refreshList();
                    parent.layer.close(ind);
                    var index = parent.layer.getFrameIndex(window.name);
                    parent.layer.close(index);// 关闭窗口
                });
            },
            success: function (res) {
                var msg = '添加成功';
                if (res.code != 200) {
                    msg = '添加成功，更新基层医疗签约状态失败，请及时处理';
                }
                parent.layer.alert(msg, {icon: 1}, function(ind){
                    parent.refreshList();
                    parent.layer.close(ind);
                    var index = parent.layer.getFrameIndex(window.name);
                    parent.layer.close(index);// 关闭窗口
                });
            }
        });
    }

    function validate() {
        $('#resident_form').validate({
            submitHandler: function (form) {
                var data = $(form).serialize();
                var action = $(form).attr("action");

                type_ids = '';
                $("input[title='key']:checked").each(function(){
                    type_ids += $(this).attr('id') + ',';
                });
                data += '&type_ids=' + type_ids;

                $.ajax({
                    cache: false,
                    type: "POST",
                    url: action,
                    dataType: "json",
                    data: data,
                    async: false,
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        toastr.error("操作失败,错误代码[" + XMLHttpRequest.status + "]");
                    },
                    success: function(res) {
                        if (res.code == 0) {
                            saveqyinfo();
                        } else {
                            toastr.error(res.msg || "失败");
                        }
                    }
                });
            },
            rules: {// 配置验证规则，key就是被验证的dom对象，value就是调用验证的方法(也是json格式)
                title: {
                    required: true,
                    maxlength: 48
                },
                idcard: {
                    required: true,
                    maxlength: 18
                },
                mobile: {
                    required: true,
                    digits: true,
                    rangelength: [8, 12]
                },
                address: {
                    required: true,
                    maxlength: 100
                }
            },
            errorPlacement: function(error, element) {
                element.parent().append(error);
                if(element.hasClass("i-checks")){
                    element.parents(".form-group").find("div").first().append(error);
                }else{
                    element.parent().append(error);
                }
            }
        });
    }

    function save() {
        var img1 = $("#src").val();
        var img2 = $("#src1").val();
        var img3 = $("#src2").val();

        type_ids = '';
        $("input[title='key']:checked").each(function(){
            type_ids += $(this).attr('id') + ',';
        });

        if(type_ids == null || type_ids==undefined||type_ids==''){
            parent.layer.msg('请选择人群分类');
            return ;
        }

        if(img1 == null || img1==undefined || img1 == ''){
            parent.layer.msg("请上传身份证正面");
            return;
        }

        if(img2 == null || img2==undefined || img2 == ''){
            parent.layer.msg("请上传身份证反面");
            return;
        }

        if(img3 == null || img3==undefined || img3 == ''){
            parent.layer.msg("请上传签约凭证");
            return;
        }


        var signLabel = $('#sign_label').html();
        if (signLabel && signLabel == '该身份证已签约') {
            parent.layer.alert(signLabel, {icon: 5, time: 2000});
            retrun;
        }
        validate();
        $('#resident_form').submit();
    }

    function init_src() {
        init_uploader('uploaderLogoUrl', 'srcView', 'src');
        init_uploader('uploaderLogoUrl1', 'srcView1', 'src1');
        init_uploader('uploaderLogoUrl2', 'srcView2', 'src2');
    }

    function init_uploader(id, view_id, url_id,del_btn) {
        $('#'+id).multiupf({
            uploader: '${image_upload_url}',
            fileExts: '*.png;*.jpg;', fileDesc: '*.png;*.jpg;',
            progress: function (data, queue) {
                if (queue.indexOf(id) > -1) {
                    $('#'+view_id).html("上传中...");
                }
            },
            complete: function (result, queue) {
                var url = result.data[0];
                if (queue.indexOf(id) > -1) {
                    $('#'+view_id).html('<img data-img src="' + url + '"  width="100%" height="100%">');
                    $('#'+url_id).val(url);
                    $("#"+del_btn).show();
                }
            }
        });
    }

    function init_uploader1(id, view_id, url_id,del_btn) {
        $('#'+id).multiupf({
            uploader: '${image_upload_url}',
            fileExts: '*.png;*.jpg;', fileDesc: '*.png;*.jpg;',
            progress: function (data, queue) {
                if (queue.indexOf(id) > -1) {
                    $('#'+view_id).html("上传中...");
                }
            },
            complete: function (result, queue) {
                var url = result.data[0];
                if (queue.indexOf(id) > -1) {
                    $('#'+view_id).html('<img data-img src="' + url + '"  width="100%" height="100%">');
                    $('#'+url_id).val(url);
                    $("#"+del_btn).show();
                }
            }
        });
    }

    function init_uploader2(id, view_id, url_id,del_btn) {
        $('#'+id).multiupf({
            uploader: '${image_upload_url}',
            fileExts: '*.png;*.jpg;', fileDesc: '*.png;*.jpg;',
            progress: function (data, queue) {
                if (queue.indexOf(id) > -1) {
                    $('#'+view_id).html("上传中...");
                }
            },
            complete: function (result, queue) {
                var url = result.data[0];
                if (queue.indexOf(id) > -1) {
                    $('#'+view_id).html('<img data-img src="' + url + '"  width="100%" height="100%">');
                    $('#'+url_id).val(url);
                    $("#"+del_btn).show();
                }
            }
        });
    }

</script>
</body>
</html>
